package helloworld.dao;

import helloworld.example.customer.CustomerDetailObject;
import helloworld.example.customer.dao.DAOException;
import helloworld.example.customer.dao.msaccess.CustomerDAO_AccessImpl;
import helloworld.example.exception.ErrorLevel;
import helloworld.common.DbSQLCommon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author TUYEN-DM
 * <p>2009/04/20</p> 
 * <p>DAO class for Database connection</p>
 */
public class ConnectionDao {

	private DbSQLCommon clsCommonDbSQL;
		
	/**
	 * @author Tuyen-DM
	 *         <p>
	 *         Database connection getter
	 *         </p>
	 * @return
	 * @throws DAOException
	 */
	protected Connection getConnnection() throws DAOException {
		Connection dbConnection = null;
		
		try {
			String userName = clsCommonDbSQL.fncGetResourceSQL("db-config", "username");
			String password = clsCommonDbSQL.fncGetResourceSQL("db-config", "userpassword");
			String url = clsCommonDbSQL.fncGetResourceSQL("db-config", "database_url");			
			Class.forName(clsCommonDbSQL.fncGetResourceSQL("db-config", "database_Server"));
			dbConnection = DriverManager.getConnection(url, userName, password);
			System.out.println("Database connection established");

		} catch (ClassNotFoundException cfe) {
			throw new DAOException(cfe, "error.database.config", null,
					ErrorLevel.FATAL);
		} catch (SQLException se) {
			throw new DAOException(se, "error.database.config", null,
					ErrorLevel.FATAL);
		}
		return dbConnection;
	}
	
	/**
	 * debug test
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			CustomerDAO_AccessImpl dao = new CustomerDAO_AccessImpl();
			CustomerDetailObject cust = dao
					.fetchDetail("antishyness@yahoo.com");
			System.out.println(cust);
		} catch (DAOException de) {
			// TODO: handle exception
			Log log = LogFactory.getLog("CustomerDAO");
			de.log(log);
		}
	}
}
